import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STRequestOptions, STData, STChange } from '@delon/abc/st';
import { SFUISchema, SFSchema, SFComponent, SFDateWidgetSchema } from '@delon/form';
import { ShipperBaseService, DynamicSettingModalComponent, SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { AccountDetailComponent } from 'src/app/shared/components/account-detail/account-detail.component';
import { UsermanageService } from '../../../services/usercenter.service';

@Component({
  selector: 'app-freight-config',
  templateUrl: './freight-config.component.html',
  styleUrls: ['../../../../commom/less/commom-table.less']
})
export class FreightConfigComponent extends BasicTableComponent implements OnInit {
  schema: SFSchema = this.initSF();
  columns: STColumn[] = this.initST();
  selectedRows: any[] = [];

  @ViewChild('IWModal', { static: false })
  IWModal!: any;
  @ViewChild('roleModal', { static: false })
  roleModal!: any;
  ltdId: any = [];
  roles: any = [];
  networkTransporter = null;
  roleId = null;
  constructor(
    public service: UsermanageService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  search() {
    this.st?.load(1);
  }

  ngOnInit() {
    this.initST();
    this.loadltdId();
    this.loadRoles();
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { listSource: 1 });
    if (this.sf?.value) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value
      });
      if (this.sf?.value.createTime) {
        Object.assign(requestOptions.body, {
          createTime: {
            start: this.sf?.value.createTime[0],
            end: this.sf?.value.createTime[1]
          }
        });
      }
    }
    this.selectedRows = [];
    return requestOptions;
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  settingAction(item?: any) {
    const modal = this.modal.create({
      nzTitle: '配置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '2',
        spareBusinessId: item.networkTransporter,
        businessId: item.id,
        formatTypeList: (item: any[]) => [
          ...item,
          {
            name: '权限配置',
            configType: 1,
            items: [
              {
                itemType: 999
              }
            ]
          },
          {
            name: '费率变更记录',
            configType: 2,
            items: [
              {
                itemType: 999
              }
            ]
          }
        ]
      },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load(1);
      }
    });
  }

  editRoleBatch() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择企业');
      return;
    }
    this.roleId = null;
    const modal = this.modal.create({
      nzTitle: '修改角色',
      nzContent: this.roleModal,
      nzOnOk: () => {
        if (!this.roleId) {
          return false;
        }
        this.service
          .request(this.service.$api_update_enter_role_batch, {
            enterpriseIdList: this.selectedRows.map(i => i.id),
            roleId: this.roleId
          })
          .subscribe((res: Array<string>) => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              this.st.load(1);
              modal.destroy();
            }
          });
        return false;
      }
    });
  }

  editIWBatch() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择企业');
      return;
    }
    this.networkTransporter = null;
    const modal = this.modal.create({
      nzTitle: '修改网络货运人',
      nzContent: this.IWModal,
      nzOnOk: () => {
        if (!this.networkTransporter) {
          return false;
        }
        this.service
          .request(this.service.$api_update_enter_newowork_batch, {
            enterpriseIdList: this.selectedRows.map(i => i.id),
            networkTransporterId: this.networkTransporter
          })
          .subscribe((res: Array<string>) => {
            if (res && res.length === 0) {
              this.service.msgSrv.success('修改成功');
              this.st.load(1);
              modal.destroy();
            } else {
              this.service.msgSrv.error(`企业${res?.join(',')}修改失败`);
              modal.destroy();
              this.st.load();
            }
          });
        return false;
      }
    });
  }

  exportList() {
    const params = { listSource: 1, pageSize: -1 };
    if (this.sf) {
      Object.assign(params, {
        ...this.sf?.value
      });
    }
    this.service.downloadFile(this.service.$api_export_freight_config, params);
  }
  loadltdId() {
    this.service.getNetworkFreightForwarder().subscribe(res => {
      if (res) {
        this.ltdId = res;
      }
    });
  }
  loadRoles() {
    this.service.getRoles({ enterpriseId: 0, projectId: 0 }).subscribe(res => {
      if (res) {
        this.roles = res;
      }
    });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        enterpriseName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        networkTransporter: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        createTime: {
          title: '注册时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true
          } as SFDateWidgetSchema
        }
      }
    };
  }

  initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '企业名称', className: 'text-center', index: 'enterpriseName', width: 350 },
      { title: '网络货运人', className: 'text-center', index: 'netTranName', width: 160 },
      {
        title: '货源单费率',
        className: 'text-right',
        index: 'goodsSurchargeRatio',
        width: 130,
        format: item => `${item.goodsSurchargeRatio}%`
      },
      {
        title: '合同单费率',
        className: 'text-right',
        index: 'contractSurchargeRatio',
        width: 130,
        format: item => `${item.contractSurchargeRatio}%`
      },
      {
        title: '合同单业务量（万元）',
        index: 'contractQuota',
        width: 170,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.contractQuota }) }
      },
      {
        title: '货源单业务量（万元）',
        index: 'goodsQuota',
        width: 170,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.goodsQuota }) }
      },
      {
        title: '注册时间',
        index: 'createTime',
        width: 180,
        className: 'text-right'
      },
      {
        title: '操作',
        width: '90px',
        fixed: 'right',
        className: 'text-center',
        buttons: [
          {
            text: '配置',
            click: item => this.settingAction(item)
          }
        ]
      }
    ];
  }
}
